﻿using System;
using System.Collections.Generic;
using System.Linq;
using MDT_MonitorModel;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

// Pour en savoir plus sur le modèle d'élément Page Éléments groupés, consultez la page http://go.microsoft.com/fwlink/?LinkId=234231

namespace MDT_Metro_monitoring
{
    /// <summary>
    /// Page affichant une collection groupée d'éléments.
    /// </summary>
    public sealed partial class GroupedItems : MDT_Metro_monitoring.Common.LayoutAwarePage
    {
        private DispatcherTimer updateTimer;
        private Type type;

        public GroupedItems()
        {
            this.InitializeComponent(); 
            SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
        }

        void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            args.Request.ApplicationCommands.Clear();
            SettingsCommand cmd = new SettingsCommand("sample", "Servers management", (uiCommand) =>
            {
                openServerManagementSnapIn();
            });

            args.Request.ApplicationCommands.Add(cmd);

        }


        private void openServerManagementSnapIn()
        {
            Popup _settingsPopup = new Popup();
            App.updateAvailable = false;
            //_settingsPopup.Closed += OnPopupClosed;
            //_settingsPopup.LostFocus += OnFocusLost;
            //_settingsPopup.PointerCaptureLost += OnPointerCaptureLost;
            //Window.Current.Activated += OnWindowActivated;
            _settingsPopup.IsLightDismissEnabled = true;
            _settingsPopup.Width = 646;
            _settingsPopup.Height = Window.Current.Bounds.Height;

            ServerManagementSettings mypane = new ServerManagementSettings();
            mypane.Width = 646;
            mypane.Height = Window.Current.Bounds.Height;


            _settingsPopup.Child = mypane;
            _settingsPopup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - 646);
            _settingsPopup.SetValue(Canvas.TopProperty, 0);
            _settingsPopup.IsOpen = true;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            this.pageTitle.Text = navigationParameter.ToString();
            if ((String)navigationParameter == "Servers")
            {
                //from cp in App.Servers group cp by cp.NbClientError into grp orderby grp.Key select grp;
                var result = from server in (from srv in App.Servers orderby srv.NbClientError, srv.NbClientWarning select srv) group server by server.Status into grp orderby grp.Key select grp;
                this.DefaultViewModel["Groups"] = result;
                type = typeof(Server);
            }
            else if ((String)navigationParameter == "Computers")
            {
                loadComputers();
                type = typeof(Computer);
            }

            updateTimer = new DispatcherTimer();
            updateTimer.Interval = new TimeSpan(0, 0, 10);
            updateTimer.Tick += UpdateUI;
            updateTimer.Start();
        }

        private void UpdateUI(object sender, object e)
        {
            if (App.updateAvailable)
            {

                if (type == typeof(Server))
                {
                    var result = from server in (from srv in App.Servers orderby srv.NbClientError, srv.NbClientWarning select srv) group server by server.Status into grp orderby grp.Key select grp;
                    this.DefaultViewModel["Groups"] = result;
                }
                else if (type == typeof(Computer))
                {
                    loadComputers();
                }
            }
        }

        private async void loadComputers()
        {

            List<Computer> dictionary = new List<Computer>();
            foreach (Server srv in App.Servers)
            {
                if (srv.Online)
                {
                    srv.Clients = (List<Computer>)await srv.ClientData.LoadComputersAsync();
                    dictionary.AddRange(srv.Clients);
                }
            }
            //Groups all computer into one single group, instead of one group per computer
            //var result = from cp in dictionary group cp by true into grp orderby grp.Key select grp;
            var result = from comp in (from cp in dictionary orderby cp.PercentComplete descending select cp) group comp by comp.Status into grp select grp;

            this.DefaultViewModel["Groups"] = result;
        }

        private void itemGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem.GetType() == typeof(Computer))
            {
                var item = (Computer)e.ClickedItem;
                this.Frame.Navigate(typeof(ItemDetailPage), item);
            }
            else if (e.ClickedItem.GetType() == typeof(Server))
            {
                var item = (Server)e.ClickedItem;
                this.Frame.Navigate(typeof(ServerDetailPage), item);
            }
            else
            {

            }
        }
    }
}
